package com.project.auth.utils;

import com.project.auth.model.system.SysMenu;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description
 * @Author : XIAOMING
 * @create 2023/4/20 15:08
 */
public class MenuHelper {
    /**
     * 使用递归方法构建菜单
     *
     * @param sysMenuList
     * @return
     */
    public static List<SysMenu> buildTree(List<SysMenu> sysMenuList) {
        //创建list集合,用于保存最终数据
        ArrayList<SysMenu> trees = new ArrayList<>();
        //将所有菜单数据遍历
        for (SysMenu sysMenu : sysMenuList) {
            if (sysMenu.getParentId().longValue() == 0) {
                trees.add(getChildren(sysMenu, sysMenuList));
            }
        }

        return trees;
    }

    public static SysMenu getChildren(SysMenu sysMenu, List<SysMenu> sysMenuList) {
        sysMenu.setChildren(new ArrayList<SysMenu>());
        //遍历菜单数据,判断id和parentId对应关系
        for (SysMenu item : sysMenuList) {
            if (sysMenu.getId().longValue() == item.getParentId().longValue()) {
                if (sysMenu.getChildren() == null) {
                    sysMenu.setChildren(new ArrayList<>());
                }
                sysMenu.getChildren().add(getChildren(item, sysMenuList));
            }
        }
        return sysMenu;
    }
}
